<?php
namespace app\api\controller\vppz;


use app\common\library\token\driver\Redis;
use think\Cache;

use \app\admin\model\vppz\Slide as SlideModel;
use \app\admin\model\vppz\Nav as NavModel;
use \app\admin\model\vppz\Page as PageModel;
use \app\admin\model\vppz\Hospital as HospitalModel;
use \app\admin\model\vppz\Service as ServiceModel;
use \app\admin\model\vppz\Staff as StaffModel;
use \app\admin\model\vppz\VipPackage as VipPackageModel;

use \addons\vppz\library\Vpower;


//use EasyWeChat\Factory as EasyWeChatFactory;

class Index extends App
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    public function _initialize(){
        parent::_initialize();

		$this->SlideModel = new SlideModel;
		$this->NavModel = new NavModel;
		$this->PageModel = new PageModel;

		$this->HospitalModel = new HospitalModel;
		$this->ServiceModel = new ServiceModel;

		$this->StaffModel = new StaffModel;
        $this->vipcardModel = new \app\admin\model\vppz\VipCard;
        $this->userModel = new \app\admin\model\vppz\User;
        $config = \think\App::initCommon();
    }


    /**
     * 运营城市区选择页
     */
    public function areas(){

		//$citys = pdo_fetchall('SELECT * FROM ' .tablename('vp_pz_city') . ' where  uniacid = :uniacid AND status=1 AND is_del=0 order by sort desc', array(':uniacid' => $_W['uniacid']));

		$areas = $this->AreaModel->field('id,name')->where(['app_id'=>$this->app_id,'use_switch'=>1])->order('weigh', 'desc')->select();


		/***
		$WxappApi = EasyWeChatFactory::miniProgram([
			'app_id'    => $this->_cfg['wxapp_id'],
			'secret'    => $this->_cfg['wxapp_secret'],
			//'token'     => 'easywechat',
			'log' => [
				'level' => 'debug',
				'file'  => '/tmp/easywechat.log',
			],
			// ...
		]);

		$mine = $this->_mine;

		$postdata=[
			'first' => array(
				'value' => '有新的服务订单',
				'color' => '#f73959'
			),
			'keyword1' => array(
				'value' => $this->_area['name']
			),
			'keyword2' => array(
				'value' => '测试订单标题'//$order['title']
			),
			'keyword3' => array(
				'value' => '测试keyword3'//$keyword3
			),
			'remark' => array(
				'value' => '测试remark'//$remark
			)
		];

		// 测试模板消息
		$ret = $WxappApi->uniform_message->send([

			'touser' => $mine['openid'],
			//'template_id' => $this->_cfg['nt_order_new'],
			//'form_id' => $this->_cfg['nt_order_new'],
			'mp_template_msg'=>[
				'appid'=>$this->_cfg['mpappid'],
				'template_id'=>$this->_cfg['nt_order_new'],
				'miniprogram'=>array(
					'appid'=>$this->_cfg['wxapp_id'],
					'pagepath'=>'vp_pz/pages/staff/index',
				),
				'data'=>$postdata
			]

		]);
		***/


		$this->success('',array(
			'now'=>time(),
			'areas'=>$areas,
			//'ret'=>$ret
		));
	}


    /**
     * 首页
     */
    public function index(){
		$area=$this->_area;
		$mine = $this->_mine;

		// 幻灯
		$slides = $this->SlideModel->field('id,pic_image,stype,stype_link,title')
            ->where(['app_id'=>$this->app_id,'use_switch'=>1,'area_id'=>$area['id'],'channel'=>1])
            ->order('weigh', 'desc')->select();

		// 导航
		// 两格导航
		$nav2s = $this->NavModel->field('id,pic_image,stype,stype_link,title,tcolor')->where(['app_id'=>$this->app_id,'use_switch'=>1,'area_id'=>$area['id'],'cat'=>4])->order('weigh', 'desc')->select();
		$navs = $this->NavModel->field('id,pic_image,stype,stype_link,title,tcolor')->where(['app_id'=>$this->app_id,'use_switch'=>1,'area_id'=>$area['id'],'cat'=>5])->order('weigh', 'desc')->select();

		// 获取医院列表
		$hospitals = $this->HospitalModel->field('id,name,avatar,rank,label,intro')
            ->where(['app_id'=>$this->app_id,'use_switch'=>1,'area_id'=>$area['id'],'is_top'=>1,'is_local'=>2,'is_kuajing'=>2])
            ->order('weigh', 'desc')
            ->group('name')
            ->select();

        $config = \think\App::initCommon();
        if(empty($hospitals) === FALSE){
            foreach ($hospitals as $k=>$v){
                $hospitals[$k]['rank'] = $config['hospital_level'][$v['rank']]??'三级';
                $hospitals[$k]['label'] = $config['hospital_label'][$v['label']]??'综合医院';
            }
        }
		/**
		// 获取医院列表
		$hospitals = pdo_fetchall('SELECT id,name,avatar,rank,label,intro FROM ' .tablename('vp_pz_hospital') . ' where  uniacid = :uniacid AND city_id=:city_id AND status=1 AND is_del=0 order by sort desc', array(':uniacid' => $_W['uniacid'],':city_id'=>$city['id']));
		for($i=0;$i<count($hospitals);$i++){
			$hospitals[$i]['avatar']=VP_IMAGE_URL($hospitals[$i]['avatar']);
		}
		**/

		// 是否有专属服务员
		$my_staff=null;
		if($area['staff_card']==1 && $mine['my_staff_id']>0){
			$my_staff=$this->StaffModel->field('id,nickname,avatar,sex,age,mobile')->where(['app_id'=>$this->app_id,'id'=>$mine['my_staff_id'],'status'=>20,'stop_switch'=>0])->find();
		}

		$this->success('',array(
			'now'=>time(),
			'slides'=>$slides,
			'nav2s'=>$nav2s,
			'navs'=>$navs,
			'hospitals'=>$hospitals,
			'my_staff'=>$my_staff
		));
    }
    public function checkvip(){
        $vipcode = input('vipcode','');
        if(empty($vipcode) === FALSE){
            $res = $this->vipcardModel->where(['code'=>$vipcode])->find();
            if(empty($res) === FALSE){
                $res->is_empty = 0;
                $this->success('',$res);
            }
        }
        $this->success('',array(
            'is_empty'=>1
        ));
    }
    //激活vip
    public function jihuovip(){
        $vipcode = input('vipcode','');
        $mine = $this->_mine;
        if(empty($vipcode) === FALSE){
            $res = $this->vipcardModel->where(['code'=>$vipcode])->find();
            if(empty($res) === FALSE){

		        $VipPackageModel = new VipPackageModel();
                //获取套餐
                $package = $VipPackageModel->where(['id'=>$res->vip_package_id])->find();
                if($res->status == 0){
                    //激活获取延期
                    $this->userModel->startTrans();
                    $userInfo = $this->userModel->where(['id'=>$mine['id']])->find();
                    $opera = [];
                    if($userInfo->is_vip){
                        //todo 判断当前卡和已有身份是否冲突
                        if($package->channel == $userInfo->channel) {
                            //延期
                            $opera[] = $this->userModel->save(array(
                                'updatetime' => time(),
                                'content' => $package->content,
                                'expire_time' => datetime(strtotime('+'.$package->duration.' month', strtotime($userInfo->expire_time)), 'Y-m-d H:i:s')
                            ), ['id' => $mine['id']]);
                            $opera[] = $this->vipcardModel->save(array(
                                'status' => 1,
                                'updatetime' => time()
                            ), array(
                                'code' => $vipcode
                            ));
                        }else{
                            $opera[] = false;
                             $this->success('',array(
                                'is_status'=>4,
                                 'msg'=>'您当前的会员身份与会员码不符，请到期后继续操作'
                            ));
                        }
                    }else{
                        $opera[] = $this->userModel->save(array(
                            'updatetime'=>time(),
                            'is_vip'=>1,
                            'content'=>$package->content,
                            'vip_time'=>datetime(time(),'Y-m-d H:i:s'),
                            'expire_time'=>datetime(strtotime('+'.$package->duration.' month', time()),'Y-m-d H:i:s')
                        ),['id'=>$mine['id']]);
                        $opera[] = $this->vipcardModel->save(array(
                            'status'=>1,
                            'updatetime'=>time()
                        ),array(
                            'code'=>$vipcode
                        ));
                    }

                    if(\Tools::checkArrayResult($opera)){
                        $this->userModel->commit();
                        $this->success('',array(
                            'is_status'=>0,
                            'msg'=>'成功'
                        ));
                    }else{
                        $this->userModel->rollback();
                        $this->success('',array(
                            'is_status'=>3,
                            'msg'=>'激活失败'
                        ));
                    }
                }else{
                    $this->success('',array(
                        'is_status'=>2,
                        'msg'=>'会员码已激活'
                    ));
                }
            }
        }
        $this->success('',array(
            'is_status'=>1,
            'msg'=>'会员码异常，请联系管理员'
        ));
    }
	// 根据前端坐标，定位所在城市和运营区
    public function location(){
        $cfg = $this->_cfg;

		if(empty($cfg['qmap_key'])){
			$this->error('未配置腾讯地图APPKEY');
		}

		$lat = input('lat');
		$lng = input('lng');
		if(!($lat>0 && $lng>0)){
			$this->error('定位信息获取失败');
		}

		// 查询所在城市
		//$res = VP_HTTP('https://apis.map.qq.com/ws/geocoder/v1/',array('location'=>$lat.','.$lng,'key'=>$cfg['qmap_key']));
		$res = \fast\Http::post("https://apis.map.qq.com/ws/geocoder/v1/", ['location'=>$lat.','.$lng,'key'=>$cfg['qmap_key']]);
		$res = json_decode($res,true);
		if($res && $res['result'] && $res['result']['address_component']){
			$minePos=array(
				'lng'=>$lng,
				'lat'=>$lat
			);
			$minePos['province'] = $res['result']['address_component']['province'];
			$minePos['city'] = $res['result']['address_component']['city'];
			$minePos['district'] = $res['result']['address_component']['district'];
			$minePos['address'] = $res['result']['address_component']['street'].$res['result']['address_component']['street_number'];

			if(input('submit')=='pos'){
				//return $this->result(0,'',$minePos);
				$this->success('',$minePos);
			}else{
				// 为保护用户隐私，最小化原则，不再存储用户位置
				// 优先定位区县
				$the_area = $this->AreaModel->where(['app_id'=>$this->app_id,'use_switch'=>1,'district'=>$minePos['district']])->find();

				// 没有则定位城市
				if(empty($the_area)){
					$the_area = $this->AreaModel->where(['app_id'=>$this->app_id,'use_switch'=>1,'city'=>$minePos['city'],'district'=>''])->find();
				}
				// 判断该城市是否开通
				//$the_city = pdo_fetch('SELECT id,name FROM ' .tablename('vp_pz_city') . ' where  uniacid = :uniacid AND is_del=0 AND status=1 AND name=:name ', array(':uniacid' => $_W['uniacid'],':name' => $minePos['city']));

				if(empty($the_area)){
					$this->error('您所在的地区“'.$minePos['city'].'”尚未开通，可手动切换到指定地区');
					//$this->error('您所在的城市“'.$minePos['city'].'”尚未开通，可手动切换到指定城市');
				}

				$this->success('',$the_area);
				//return $this->result(0,'',$the_city);
			}
		}else{
			$this->error('定位失败，请手动选择所在城市');
			//$this->error('定位失败，请手动选择所在城市');
		}
    }

	public function search(){
		// 找医院
		$cfg = $this->_cfg;
		$area = $this->_area;

		$start=input('start');
		if(!isset($start) || empty($start) || intval($start<=0)){
			$start=0;
		}else{
			$start=intval($start);
		}
		$limit=20;

		$where=[
			'app_id'=>$this->app_id,
			'area_id'=>$area['id'],
			'use_switch'=>1
		];

		$search = input('search');
		$search = trim($search);
		if(empty($search)){
			$this->error('查找内容不能为空');
		}
		$where['name']=['LIKE',('%'.$search.'%')];

		$list = $this->HospitalModel->where($where)->limit($start,$limit)->select();

		$more=1;
		if(empty($list) || count($list)<$limit){
			$more=0;
		}
        if(empty($list) === FALSE){
                foreach ($list as $k=>$v){
                    $list[$k]['rank'] = $config['hospital_level'][$v['rank']]??'三级';
                    $list[$k]['label'] = $config['hospital_label'][$v['label']]??'综合医院';
                }
            }
		$start+=count($list);

		$this->success('',array(
			'now'=>time(),
			'list'=>$list,
			'start'=>$start,
			'more'=>$more
		));
	}

	public function tag(){
		$tag = input('tag');

		//$where = " uniacid = :uniacid AND status=1 AND is_del=0 AND tags LIKE '%".$tag."%' ";
		//$params = array(':uniacid' => $_W['uniacid']);

		$where=[
			'app_id'=>$this->app_id,
			'use_switch'=>1,
			'tags'=>['LIKE',('%'.$tag.'%')]
		];

		// 获内容记录
		//$services =  pdo_fetchall('SELECT id,code,name,logo,intro,price FROM ' .tablename('vp_pz_service') . ' WHERE '. $where .' ',$params);

		$services = $this->ServiceModel->field('id,code,name,icon_image,logo_image,intro,price')->where($where)->select();


		$this->success('',array(
			'now'=>time(),
			'services'=>$services
		));

	}


	public function html(){
		$mine = $this->_mine;

		$cmd = input('cmd');

		$title = '';
		$content = '';
		$server = 0;

		if($cmd=='slide'){
			$id=input('id');
			if(!($id>0)){
				$this->error('请选择要查看的内容');
			}

			$slide = $this->SlideModel->field('id,title,stype_content')->where(['app_id'=>$this->app_id,'use_switch'=>1])->find($id);

			if(empty($slide)){
				$this->error('该内容不存在或已删除');
			}
			$title = $slide['title'];
			$content = $slide['stype_content'];
		}else if($cmd=='nav'){
			$id=input('id');
			if(!($id>0)){
				$this->error('请选择要查看的内容');
			}

			$nav = $this->NavModel->field('id,title,stype_content')->where(['app_id'=>$this->app_id,'use_switch'=>1])->find($id);

			if(empty($nav)){
				$this->error('该内容不存在或已删除');
			}
			$title = $nav['title'];
			$content = $nav['stype_content'];
		}else if($cmd=='page'){
			$id=input('id');
			if(!($id>0)){
				$this->error('请选择要查看的内容');
			}

			$page = $this->PageModel->field('id,title,content,server_switch')->where(['app_id'=>$this->app_id])->find($id);

			if(empty($page)){
				$this->error('该内容不存在或已删除');
			}
			$title = $page['title'];
			$content = $page['content'];
			$server = $page['server_switch'];
		}

		$this->success('',array(
			'title'=>$title,
			'content'=>$content,
			'server'=>$server
		));
	}


    /**
     * 获取当前区域的陪护师
     */
    public function staffs(){
		$area=$this->_area;
		$mine = $this->_mine;

		$cmd = input('cmd');
		if($cmd=='change'){
			$staff_id=input('staff_id');

			$this->UserModel->where(['app_id'=>$this->app_id,'id'=>$mine['id']])->data(['my_staff_id'=>$staff_id])->update();

			$my_staff=$this->StaffModel->field('id,nickname,avatar,sex,age,mobile')->where(['app_id'=>$this->app_id,'id'=>$staff_id,'status'=>20,'stop_switch'=>0])->find();

			$this->success('已选择',['my_staff'=>$my_staff]);
		}else{
			$staffs = $this->StaffModel->field('id,user_id,nickname,avatar,sex,age,mobile,realname')->where(['app_id'=>$this->app_id,'area_id'=>$area['id'],'status'=>20,'stop_switch'=>0])->select();


			// 是否有专属服务员
			$my_staff=null;
			if($area['staff_card']==1 && $mine['my_staff_id']>0){
				$my_staff=$this->StaffModel->field('id,nickname,avatar,sex,age,mobile')->where(['app_id'=>$this->app_id,'id'=>$mine['my_staff_id'],'status'=>20,'stop_switch'=>0])->find();
			}

			$this->success('',array(
				'now'=>time(),
				'staffs'=>$staffs,
				'my_staff'=>$my_staff
			));
		}
	}
    public function getDistance(){
        $area=$this->_area;
		$mine = $this->_mine;

		$hospitalid = input('hospitalid');
		$lat = input('lat');
		$lng = input('lng');
        $hospitals = $this->HospitalModel->find($hospitalid);
        $distance = \Tools::getDistance($hospitals['lng'],$hospitals['lat'],$lng,$lat);
        if($distance > 1000){
            $this->error('超出核销范围，暂时无法进行核销');
        }else{
            $this->success('',true);
        }

    }
    //获取气泡数据
    public function getqipaodata(){
        $redis = new Redis();
        $key = "bangyetang_qipao_info";
        $result = [];
        for ($i = 0;$i < 10;$i++){
            $data = $redis->rpop($key);
            $data = json_decode($data,true);
            if(empty($data) === FALSE) {
                $data['user'] = maskName($data['user']);
                array_push($result, $data);
            }else{
                $surnames = ['王', '李', '张', '刘', '陈', '杨', '黄', '赵', '吴', '周','徐', '孙', '马', '朱', '胡', '林', '郭', '何', '高', '罗','郑', '梁', '谢', '宋', '唐', '许', '韩', '冯', '邓', '曹','彭', '曾', '肖', '田', '董', '袁', '潘', '于', '蒋', '蔡','余', '杜', '叶', '程', '苏', '魏', '吕', '丁', '任', '沈','姚', '卢', '姜', '崔', '钟', '谭', '陆', '汪', '范', '金'];
                $randomKey = array_rand($surnames);

                // 根据随机键名获取对应的姓氏
                $randomLastName = $surnames[$randomKey];
                switch ($i){
                    case 0:
                        $ifno = array(
                            'user'=>$randomLastName.'**',
                            'action'=>'购买了家庭医生会员'
                        );
                        break;
                    case 1:
                        $ifno = array(
                            'user'=>$randomLastName.'**',
                            'action'=>'购买了居家康养套餐'
                        );
                        break;
                    case 2:
                        $ifno = array(
                            'user'=>$randomLastName.'**',
                            'action'=>'购买了家庭医生会员'
                        );
                        break;
                    case 3:
                        $ifno = array(
                            'user'=>$randomLastName.'**',
                            'action'=>'购买了护理设备'
                        );
                        break;
                    case 4:
                        $ifno = array(
                            'user'=>$randomLastName.'**',
                            'action'=>'购买了家庭医生会员'
                        );
                        break;
                    case 5:
                        $ifno = array(
                            'user'=>$randomLastName.'**',
                            'action'=>'购买了家庭医生会员'
                        );
                        break;
                    case 6:
                        $ifno = array(
                            'user'=>$randomLastName.'**',
                            'action'=>'租赁了医用设备'
                        );
                        break;
                    case 7:
                        $ifno = array(
                            'user'=>$randomLastName.'**',
                            'action'=>'购买了家庭医生会员'
                        );
                        break;
                    case 8:
                        $ifno = array(
                            'user'=>$randomLastName.'**',
                            'action'=>'购买了家庭医生会员'
                        );
                        break;
                    case 9:
                        $ifno = array(
                            'user'=>$randomLastName.'**',
                            'action'=>'购买了家庭医生会员'
                        );
                        break;
                }
                array_push($result,$ifno);
            }
        }
        $this->success('',$result);
    }
}
